<template>
  <el-table :data="bookData" style="width: 100%">
    <el-table-column label="图片" width="200" align="center">
      <template #default="{ row }">
        <img
          :src="row.coverImageUrl"
          alt=""
          style="width: 180px; height: 220px"
        />
      </template>
    </el-table-column>
    <el-table-column
      prop="title"
      label="书名"
      width="150"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="author"
      label="作者"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="description"
      label="简介"
      width="220"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="price"
      label="价格"
      width="140"
      align="center"
    ></el-table-column>
    <el-table-column label="操作" width="180" align="center">
      <template #default="{ row }">
        <el-icon
          type="primary"
          @click="addToCart(row)"
          style="font-size: 30px; color: rgb(209, 197, 68); margin: 10px"
          ><ShoppingCart
        /></el-icon>
        <el-button
          type="info"
          style="margin-top: -15px"
          @click="viewComments(row)"
          >查看评论</el-button
        >
      </template>
    </el-table-column>

    <!-- 其他列... -->
  </el-table>
  <!-- 添加评论对话框 -->
  <el-dialog title="评论详情" v-model="dialogVisible" width="50%">
    <!-- 添加评论表单，仅当isAddingReview为true时显示 -->
    <el-form
      ref="commentForm"
      :v-model="newComment"
      label-width="80px"
      v-if="isAddingReview"
    >
      <el-form-item label="评分">
        <el-input
          v-model.number="newComment.rating"
          type="number"
          :min="1"
          :max="100"
          placeholder="请输入1到100的分数"
        ></el-input>
      </el-form-item>
      <el-form-item label="评论内容">
        <el-input
          v-model="newComment.content"
          type="textarea"
          rows="4"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitComment(newComment)"
          >提交评论</el-button
        >
        <el-button @click="cancelAddingReview">取消</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="selectedBookComments" style="width: 100%">
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
      ></el-table-column>
      <el-table-column prop="rating" label="评分" width="80"> </el-table-column>
      <el-table-column prop="content" label="评论内容"></el-table-column>
      <el-table-column prop="createdAt" label="发表时间" width="180">
      </el-table-column>
    </el-table>
    <!-- 添加评论按钮 -->
    <div v-if="!isAddingReview" class="add-review-action">
      <el-button type="primary" @click="startAddingReview">评价</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { definedUser } from "@/store/store";
import API from "../../api/API";
import { ShoppingCart } from "@element-plus/icons-vue";
export default {
  name: "Category",
  components: {
    ShoppingCart,
  },

  data() {
    return {
      categoryId: 0,
      userId: definedUser().userId,
      orderId: 0,
      rawBookData: [],
      bookData: [],
      requestData: [],
      dialogVisible: false, // 控制评论对话框的显示与隐藏
      selectedBookId: 0, // 用于存储当前选择查看评论的书籍ID
      selectedBookComments: [], // 存储当前书籍的评论数据
      isAddingReview: false,
      newItem: {
        bookId: 0,
        userId: 0,
        quantity: 1,
      },
      newComment: {
        bookId: 0,
        userId: 0,
        rating: 0,
        content: "",
      },
    };
  },

  created() {
    API.getBooks()
      .then((response) => {
        this.rawBookData = response.data.data;
        console.log(this.rawBookData);
        if (this.$route.params && this.$route.params.categoryId) {
          this.categoryId = this.$route.params.categoryId;
        }
        this.bookData = this.rawBookData.filter(
          (book) => book.category.categoryId == this.categoryId
        );
      })
      .catch((error) => {
        console.error("Error fetching books:", error);
      });
  },
  beforeUpdate() {
    if (this.$route.params && this.$route.params.categoryId) {
      this.categoryId = this.$route.params.categoryId;
    }
    this.bookData = this.rawBookData.filter(
      (book) => book.category.categoryId == this.categoryId
    );
  },
  methods: {
    addToCart(book) {
      // 发送添加到购物车的事件，并附带书籍信息
      this.newItem.userId = definedUser().userId;
      this.newItem.bookId = book.bookId;

      console.log(this.newItem);
      API.addCartItem(definedUser().userId, this.newItem)
        .then((response) => {
          if (response.data.status == "200") {
            this.requestData = response.data.data;
            this.$message.success("添加成功");
          } else {
            console.error("添加购物车失败：");
          }
        })
        .catch((error) => {
          console.error("请求失败:", error);
        });
    },
    startAddingReview() {
      this.isAddingReview = true;
    },
    cancelAddingReview() {
      this.isAddingReview = false;
      this.$refs.commentForm.resetFields();
    },
    submitComment(review) {
      console.log(review);
      if (!this.newComment.content || this.newComment.content.trim() === "") {
        this.$message.error("评论内容不能为空");
        return;
      }
      API.addReview(review).then((response) => {
        if (response.data.status == "200") {
          console.log("评论添加成功");
          // 将新评论数据添加到现有评论列表中
          this.fetchComments(this.selectedBookId); // 刷新评论列表，如果需要从后端重新获取所有评论
          this.$refs.commentForm.resetFields(); // 清空表单
          this.$message.success("评论提交成功！");
        } else {
          this.$message.error("评论提交失败，请重试！");
        }
      });
    },

    viewComments(book) {
      this.newComment.userId = definedUser().userId;
      this.newComment.bookId = book.bookId;
      this.selectedBookId = book.bookId; // 记录当前选择查看评论的书籍ID
      this.fetchComments(this.selectedBookId);
      this.dialogVisible = true; // 显示对话框
    },
    fetchComments(bookId) {
      API.getReviews(bookId)
        .then((response) => {
          if (response.data.status == "200") {
            this.selectedBookComments = response.data.data;
            console.log(this.selectedBookComments);
          } else {
            // console.error("Error fetching comments:", response.data.message);
          }
        })
        .catch((error) => {
          console.error("Error fetching comments:", error);
        });
    },

    formatDate(dateString) {
      return moment(dateString).format("YYYY-MM-DD HH:mm:ss");
    },
  },
};
</script>
<style lang="less" scoped></style>
